<template>
  <div>
    <!-- 部门列表 -->
    <div class="department_card">
      <el-card class="w-[22%]">
        <template #header>
          <el-button
            type="primary"
            class="w-full"
            icon="Plus"
            @click="handleAddDepartment(0)"
          >
            添加部门
          </el-button>
        </template>

        <template #default>
          <el-scrollbar style="height: calc(100vh - 10rem)">
            <el-tree
              class="w-full"
              :data="departmentTreeTable"
              :props="{
                label: 'departmentName',
                children: 'children',
              }"
              @node-click="handleClickDepartment"
            >
              <template #default="{ node, data }">
                <div
                  class="w-full flex justify-between items-center"
                  :class="{
                    active: data.id == searchForm.departmentId,
                  }"
                  v-if="data.id == searchForm.departmentId"
                >
                  <span>{{ node.label }}</span>
                  <div>
                    <el-button
                      type="primary"
                      link
                      @click.stop="handleAddDepartment(data.id)"
                      icon="Plus"
                    >
                    </el-button>
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDeleteDepartment(data)"
                      icon="Delete"
                    >
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </template>
      </el-card>
      <el-card class="w-[22%]">
        <template #header>
          <el-button
            type="primary"
            class="w-full"
            icon="Plus"
            @click="handleAddPosition"
          >
            添加职位
          </el-button>
        </template>

        <template #default>
          <el-scrollbar style="height: calc(100vh - 10rem)">
            <el-tree
              class="w-full"
              :data="positionList"
              :props="{
                label: 'positionName',
                children: 'children',
              }"
              @node-click="handleSetting"
            >
              <template #default="{ node, data }">
                <div
                  class="w-full flex justify-between items-center"
                  :class="{
                    active: data.id == searchForm.positionId,
                  }"
                  v-if="data.id == searchForm.positionId"
                >
                  <span>{{ node.label }}</span>
                  <div>
                    <!-- <el-button
                      type="primary"
                      link
                      @click.stop="handleSetting(node, data)"
                      icon="Setting"
                    >
                    </el-button> -->
                    <el-button
                      type="danger"
                      link
                      @click.stop="handleDeletePosition(node, data)"
                      icon="Delete"
                    >
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </template>
      </el-card>
      <el-card class="w-[54%]">
        <JurisdictionManage ref="jurisdictionRef" />
      </el-card>
    </div>

    <el-drawer
      v-model="department_drawer"
      :title="departmentParentId == 0 ? '添加部门' : '添加子部门'"
      destroy-on-close
      size="35%"
    >
      <InsertDepartment
        :departmentParentId="departmentParentId"
        @handleBack="handleDepartment"
      />
    </el-drawer>

    <el-drawer
      v-model="position_drawer"
      title="添加职位"
      destroy-on-close
      size="35%"
    >
      <InsertPosition
        :departmentId="searchForm.departmentId"
        :departmentName="searchForm.departmentName"
        @handleBack="handlePosition"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import InsertDepartment from "./component/InsertDepartment.vue";
import InsertPosition from "./component/InsertPosition.vue";
import JurisdictionManage from "./component/JurisdictionManage.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetOrganizeDepartmentTree,
  GetPositionListForDepartment,
} from "../../../../../wailsjs/go/api/CustomerApi";
import {
  DeleteOrganizeDepartmentById,
  DeletePositionForDepartment,
} from "../../../../../wailsjs/go/api/DeptApi";
onMounted(() => {
  getDepartmentTree();
});

const searchForm = ref({
  departmentId: null,
  departmentName: "",
  positionId: null,
});

// 1.获取部门树
const departmentTreeTable = ref([]);
async function getDepartmentTree() {
  handleApiResponse(() => GetOrganizeDepartmentTree()).then((res) => {
    if (res.code == 0) {
      // console.log(res.data.departmentTree);
      departmentTreeTable.value = res.data.departmentTree || [];
      if (departmentTreeTable.value.length > 0) {
        handleClickDepartment(departmentTreeTable.value[0]);
      }
    }
  });
}
// 2.获取职位
const positionList = ref([]);
async function getPositionList(departmentId) {
  handleApiResponse(() => GetPositionListForDepartment({ departmentId })).then(
    (res) => {
      if (res.code == 0) {
        // console.log(res.data.list);
        positionList.value = res.data.list || [];
      }
    }
  );
}

// 1-1 点击部门
const handleClickDepartment = (data) => {
  if (data.id == searchForm.value.departmentId) return;
  searchForm.value.departmentId = data.id;
  searchForm.value.departmentName = data.departmentName;
  searchForm.value.positionId = null;
  getPositionList(data.id);
  handleRemoveApiList();
};

// 1-2 添加部门
const department_drawer = ref(false);
const departmentParentId = ref(0);
const handleAddDepartment = (parentId) => {
  departmentParentId.value = parentId;
  department_drawer.value = true;
};

const handleDepartment = (val) => {
  if (val == 1) {
    getDepartmentTree();
  }
  department_drawer.value = false;
};

// 1-3 删除部门
const handleDeleteDepartment = (data) => {
  ElMessageBox.confirm("确定删除该部门吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() => DeleteOrganizeDepartmentById({ id: data.id })).then(
      (res) => {
        if (res.code == 0) {
          ElMessage.success("删除成功");
          getDepartmentTree();
        }
      }
    );
  });
};

// 2-1 点击职位
const handleClickPosition = (data) => {
  searchForm.value.positionId = data.id;
};
// 2-2 删除职位
const handleDeletePosition = (data) => {
  ElMessageBox.confirm("此操作将永久删除该职位, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      DeletePositionForDepartment({
        departmentId: searchForm.value.departmentId,
        positionId: data.id,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("删除成功");
        getPositionList(searchForm.value.departmentId);
      }
    });
  });
};

// 2-3 添加职位
const position_drawer = ref(false);
const handleAddPosition = () => {
  if (!searchForm.value.departmentId) return ElMessage.warning("请先选择部门");

  position_drawer.value = true;
};
const handlePosition = (val) => {
  if (val == 1) {
    getPositionList(searchForm.value.departmentId);
  }
  position_drawer.value = false;
};

// 3-1 点击职位/权限
const jurisdictionRef = ref(null);
const handleSetting = (data) => {
  searchForm.value.positionId = data.id;
  jurisdictionRef.value?.getMenuList(searchForm.value.departmentId, data.id);
};
const handleRemoveApiList = () => {
  jurisdictionRef.value?.handleRemove();
};
</script>

<style scoped lang="scss">
.department_card {
  height: calc(100vh - 7rem);
  @apply w-full flex justify-between items-center;
  .el-card {
    @apply h-full;
  }
  :deep(.el-card__header),
  :deep(.el-card__body) {
    @apply p-1;
  }
  :deep(.el-tree-node__content) {
    height: 2rem;
  }
  :deep(.el-alert) {
    @apply h-[1.8rem] p-1;
  }

  .active {
    @apply w-full h-full bg-[#F5F7Fa];
  }

  .el-button + .el-button {
    @apply ml-0;
  }
}
</style>